package com.hmyd.hmyd_android.utils;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;

public class ShakeListenerUtils implements SensorEventListener {
	private Context mContext;
	private ShakeListener shakeListener;
	protected static long lastClickTime;
	
	public ShakeListenerUtils(Context context){
		this.mContext = context;
	}
	
	public void setShakeListener(ShakeListener sl){
		this.shakeListener = sl;
	}

	/**
	 * 数值变化调取
	 */
	@Override
	public void onSensorChanged(SensorEvent event) {
		// 获取传感器
		Sensor sensor = event.sensor;
		// 获取坐标轴
		float[] values = event.values;
		
		if (!isFastDoubleClick()) {
			// 获取重力加速度状态
			if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
				if (Math.abs(values[0]) > 17 || Math.abs(values[1]) > 17 || 
						Math.abs(values[2]) > 17) {
					// 处理摇晃事件
					shakeListener.onShakeListener();
				}
			}
		}
	}
	
	/**
	 *  防止在短时间重复操作 
	 */
	public static boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 300) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	/**
	 * 精度感应
	 */
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		
	}

	public interface ShakeListener {
		public void onShakeListener();
	}
}
